package com.ws.dn.web.auth;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ws.dn.mapper.user.entity.SysUser;
import com.ws.dn.mapper.user.mapper.SysRoleMapper;
import com.ws.dn.mapper.user.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailsService implements UserDetailsService {
    private SysUserMapper userMapper;
    private SysRoleMapper roleMapper;

    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public CustomUserDetailsService(SysUserMapper userMapper, SysRoleMapper roleMapper){
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过用户名从数据库获取用户信息
        EntityWrapper<SysUser> ew = new EntityWrapper<>();
        ew.eq("username",username);
        List<SysUser> users = userMapper.selectList(ew);
        if (users.size()==0) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 得到用户角色
        long rid = users.get(0).getRoleId();
        if(rid == 0){
            throw new UsernameNotFoundException("角色信息不存在");
        }
        String role = roleMapper.selectById(rid).getName();

        // 角色集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色必须以`ROLE_`开头，数据库中没有，则在这里加
        authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
        return new User(
                users.get(0).getUsername(),users.get(0).getPassword(), authorities
        );
    }
}
